package texture

import (
	. "learn-opengl/util"

	"github.com/go-gl/gl/v3.3-core/gl"
	"github.com/go-gl/mathgl/mgl32"
)

type Texture struct {
	mTexture *texture
}

func NewTexture(path string) (*Texture) {
	myT := &Texture{}
	
	img, rect, err := LoadImage(path)
	if err!=nil {
		Herr(err)
	}
	myT.mTexture = newTexture(rect.Dx(),rect.Dy(),img)

	return myT
} 

func (t *Texture)Bind(id int) {
	t.mTexture.bind(id)
}

func (t *Texture)UnBind() {
	t.mTexture.unbind()
}


type texture struct {
	tex           uint32
}

func (t *texture) bind(slot int) {
	gl.ActiveTexture(gl.TEXTURE0+uint32(slot))
	gl.BindTexture(gl.TEXTURE_2D,t.tex)
}


func (t *texture) unbind() {
	gl.BindTexture(gl.TEXTURE_2D,0)
}


func newTexture(width, height int, pixels []uint8) *texture {
	tex := &texture{}

	gl.GenTextures(1, &tex.tex)
	gl.BindTexture(gl.TEXTURE_2D,tex.tex)

	// initial data
	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(width),
		int32(height),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(pixels),
	)
	
	borderColor := mgl32.Vec4{0, 0, 0, 0}
	// nearest 产生像素风格
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	// 边框
	gl.TexParameterfv(gl.TEXTURE_2D, gl.TEXTURE_BORDER_COLOR, &borderColor[0])
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_BORDER)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_BORDER)

	// gl.GenerateMipmap(gl.TEXTURE_2D)
	return tex
}
